package com.weacar.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.nex3z.flowlayout.FlowLayout;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.bean.HomeKeyBean;
import com.weacar.bean.LoginBean;
import com.weacar.bean.TestKeyBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.ToastUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 搜索起始页
 */

public class SearchIndexActivity extends BaseActivity {


    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.flow_history)
    FlowLayout flow_history;
    @BindView(R.id.flow_hot)
    FlowLayout flow_hot;

    private List<Serializable> al_history;


    @OnClick({R.id.tv_cancel, R.id.iv_clean_history, R.id.iv_search})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                if (et_search.getText().toString().trim().equals("")) {
                    finish();
                } else {
                    et_search.setText("");
                }
                break;
            case R.id.iv_clean_history:
                MessageDialog.show(this, "提示", "是否清除历史搜索记录", "确定", "取消").setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        SharedPreferenceUtil.putList(getApplicationContext(), "history_key", null);
                        if (al_history != null) {
                            al_history.clear();
                        }
                        flow_history.removeAllViews();
                        return false;
                    }
                }).setOnCancelButtonClickListener(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        return false;
                    }
                });
                break;
            case R.id.iv_search:
                String search = et_search.getText().toString().trim();
                if (search != null && !search.equals("")) {
                    if (!al_history.contains(search)) {
                        LogUtils.d("add search = " + search);
                        al_history.add(search);
                        // 搜索历史最多保留10个
                        if (al_history.size() > 10) {
                            al_history.remove(0);
                        }
                        SharedPreferenceUtil.putList(getApplicationContext(), "history_key", al_history);
                        flow_history.removeAllViews();
                        initHistoryData();
                        et_search.setText("");
                        Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                        intent.putExtra("key", search);
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_search_index);
        AppManager.getInstance().addActivity(this);
        ButterKnife.bind(this);
        initData();
        initHistoryData();

        // 键盘搜索监听
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                // 防止2次操作
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String search = textView.getText().toString().trim();
                    if (search != null && !search.equals("")) {
                        if (!al_history.contains(search)) {
                            LogUtils.d("add search = " + search);
                            al_history.add(search);
                            // 搜索历史最多保留10个
                            if (al_history.size() > 10) {
                                al_history.remove(0);
                            }
                            SharedPreferenceUtil.putList(getApplicationContext(), "history_key", al_history);
                            flow_history.removeAllViews();
                            initHistoryData();
                            et_search.setText("");
                            Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                            intent.putExtra("key", search);
                            startActivity(intent);
                        }
                    }
                }
                return false;
            }
        });
    }

    /**
     * 初始化搜索历史记录
     */
    public void initHistoryData() {
        al_history = SharedPreferenceUtil.getList(getApplicationContext(), "history_key");
        if (al_history == null) {
            al_history = new ArrayList<>();
        } else {
            LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
            for (int i = 0; i < al_history.size(); i++) {
                // LogUtils.d("search = " + al_history.get(i));
                final int position = i;
                View v = inflater.inflate(R.layout.item_gv_search, null);
                TextView tv = v.findViewById(R.id.tv_key);
                tv.setText(al_history.get(i).toString());
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                        intent.putExtra("key", al_history.get(position).toString());
                        startActivity(intent);
                    }
                });
                flow_history.addView(v);
            }
        }
    }

    /**
     * 获取热门搜索
     */
    public void getHotRecommend() {
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }
        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_hot_search);
        params.setCacheMaxAge(0);
        LogUtils.d("hot_search_url = " + params.getUri());
        showLoading("数据加载中...");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("hot_search_result = " + result);
                Gson gson = new Gson();
                BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                if (baseBean != null && baseBean.getCode() == 1) {
                    try {
                        HomeKeyBean homeKeyBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), HomeKeyBean.class);
                        if (homeKeyBean != null && homeKeyBean.getMsg() != null) {
                            LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
                            for (int i = 0; i < homeKeyBean.getMsg().size(); i++) {
                                final int position = i;
                                View v = inflater.inflate(R.layout.item_gv_search, null);
                                TextView tv = v.findViewById(R.id.tv_key);
                                final HomeKeyBean.MsgBean msgBean = homeKeyBean.getMsg().get(i);
                                tv.setText(msgBean.getName());
                                tv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        String key = msgBean.getName();
                                        if (!al_history.contains(key)) {
                                            LogUtils.d("add search = " + key);
                                            al_history.add(key);
                                            // 搜索历史最多保留10个
                                            if (al_history.size() > 10) {
                                                al_history.remove(0);
                                            }
                                            SharedPreferenceUtil.putList(getApplicationContext(), "history_key", al_history);
                                            flow_history.removeAllViews();
                                            initHistoryData();
                                        }
                                        Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                                        intent.putExtra("key", key);
                                        startActivity(intent);

                                    }
                                });
                                flow_hot.addView(v);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


                closeLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeLoading();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeLoading();
            }

            @Override
            public void onFinished() {
                closeLoading();
            }
        });

    }


    public void initData() {
        getHotRecommend();
    }
}
